package traveldream.ejb.sessionBean;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import traveldream.ejb.DTO.PackageDTO;
import traveldream.ejb.DTO.SearchDTO;
import traveldream.ejb.entities.DefaultPackage;
import traveldream.ejb.entities.TransportationMean;
import traveldream.ejb.interfaces.SearchBeanLocal;

/**
 * Session Bean implementation class SearchBean
 */
@Stateless
public class SearchBean implements SearchBeanLocal {
	
	@PersistenceContext
	private EntityManager em;

    /**
     * Default constructor. 
     */
    public SearchBean() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public List<PackageDTO> search(SearchDTO sDTO) {
		// TODO Auto-generated method stub
		//List<DefaultPackage> result = em.createNativeQuery(DefaultPackage.setQuery(sDTO.getArrivalDate().toString(),sDTO.getDepartureDate().toString(),sDTO.getArrivalPlace(),sDTO.getDeparturePlace()), DefaultPackage.class).getResultList();
		Query query = em.createNamedQuery("DefaultPackage.search", DefaultPackage.class);
		query.setParameter("arr_place", sDTO.getArrivalPlace());
		query.setParameter("dep_place", sDTO.getDeparturePlace());
		query.setParameter("arr_date", sDTO.getArrivalDate());
		query.setParameter("dep_date", sDTO.getDepartureDate());
		List<DefaultPackage> result = query.getResultList();
		List<PackageDTO> pDTO=new ArrayList<PackageDTO>();
		for(int i=0;i<result.size();i++)
		{
			pDTO.add(convertToDTO(result.get(i)));
		}
		return pDTO;
	}
	
    public PackageDTO convertToDTO(DefaultPackage dP){
    	PackageDTO pDTO = new PackageDTO();
    	pDTO.setDescription(dP.getDescription());
    	pDTO.setId(dP.getId());
    	pDTO.setName(dP.getName());
    	pDTO.setNation(dP.getNation());
    	pDTO.setPrice(dP.getPrice());
    	pDTO.setIdReturn(dP.getTransport_arr().getId());
    	pDTO.setIdGoing(dP.getTransport_dep().getId());
    	pDTO.setIdExcursion(dP.getExcursion().getId());
    	pDTO.setIdHotel(dP.getHotel().getId());
    	return pDTO;
    }
    

}
